package com.zm.demo.core.leetcode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import static java.lang.System.out;

/**
 * @author zoum
 * @create 2020/1/9 15:16
 */
public class IsSymmetric {
    Map<Integer, List<Integer>> map = new HashMap<>();

    public boolean isSymmetric(TreeNode root) {
        if (root == null){
            return true;
        }
        calc(root, 0);

        List<List<Integer>>es = map.entrySet().stream().map(e -> e.getValue()).collect(Collectors.toList());
        for (int n = 0; n < es.size(); n++) {
            List<Integer> list = es.get(n);
            for (int i = 0, j= list.size()-1; i < j; i++, j--) {
                if (!Objects.equals(list.get(i),list.get(j))){
                    return false;
                }
            }

        }
        return true;
    }

    public void calc(TreeNode root, int level) {
        if (level == 0){
            map.put(level, Arrays.asList(root.val));
            calc(root.left, level+1);
            calc(root.right, level+1);
        }else{
            if (root == null){
                map.compute(level, (k, v) -> {
                    if (v == null) {
                        List l = new ArrayList();
                        l.add(null);
                        return  l;
                    }else {
                        v.add(null);
                        return v;
                    }
                });
            }else {
                map.compute(level, (k, v) -> {
                    if (v == null) {
                        List l = new ArrayList();
                        l.add(root.val);
                        return l;
                    }else {
                        v.add(root.val);
                        return v;
                    }
                });
                calc(root.left, level+1);
                calc(root.right, level+1);
            }
        }

    }





    public static void main(String[]args){
        TreeNode node3_1 = new TreeNode(3);
        TreeNode node3_2 = new TreeNode(4);

        TreeNode node2_1 = new TreeNode(2);
        node2_1.left = node3_1;
        node2_1.right = node3_2;

        TreeNode node3_3 = new TreeNode(4);
        TreeNode node3_4 = new TreeNode(3);
        TreeNode node2_2 = new TreeNode(2);
        node2_2.left = node3_3;
        node2_2.right = node3_4;

        TreeNode node1 = new TreeNode(1);
        node1.left = node2_1;
        node1.right = node2_2;
        out.println(new IsSymmetric().isSymmetric(node1));
    }
}
